package com.etoak.controller;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.properties.ImageProperties;
import com.etoak.common.core.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {

    @Autowired
    ImageProperties imageProperties;

    /**
     * 图片上传
     *
     * @param pic
     * @return
     */
    @PostMapping("/image")
    public ResultVO<String> upload(@RequestBody MultipartFile pic) {
        /* 判断是否为空 */
        if (ObjectUtils.isEmpty(pic) || pic.isEmpty()) {
            return ResultVO.failed("文件不能为空!");
        }

        /* 判断类型 */
        String contentType = pic.getContentType();
        if (!imageProperties.getTypes().contains(contentType)) {
            // ["image/png", "image/jpeg"] 转成 "png、jpeg"
            String typeString = imageProperties.getTypes().stream().map(x -> x.substring(x.lastIndexOf("/") + 1))
                    .collect(Collectors.joining("、"));
            return ResultVO.failed("仅支持" + typeString + "类型!");
        }

        /* 创建文件名称 */
        String originalFilename = pic.getOriginalFilename();
        String suffix = FileNameUtil.getSuffix(originalFilename);
        String filename = IdUtil.simpleUUID() + "." + suffix;

        /* 创建上传目录 */
        File uploadDir = new File(imageProperties.getLocation());
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        /* 创建目标文件，执行上传 */
        File destFile = new File(uploadDir, filename);
        try {
            pic.transferTo(destFile);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return ResultVO.failed("上传失败!");
        }

        String path = imageProperties.getMapping().endsWith("/") ?
                imageProperties.getMapping() + filename :
                imageProperties.getMapping() + "/" + filename;
        return ResultVO.success(path);
    }
}
